package com.zzyl.intercept;

import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import net.bytebuddy.asm.Advice;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("authorization");
        // 判断token是否为空
        if (token == null || token == "") {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);  // 401 "登录状态失效，请重新登录"
        }

        // 解析token
        try {
            Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
            if (claims == null || claims.isEmpty()) {
                throw new BaseException(BasicEnum.LOGIN_FAIL);
            }
            // 解析成功，将里面的用户id数据拿出来，存入ThreadLocal中
            Integer id = (Integer)claims.get("id");
            int intId = id;
            UserThreadLocal.set(Long.valueOf(intId));
        } catch (Exception e) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        // 满足上面的所有要求，则放行。
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //响应结束，需清理ThreadLocal中的数据，防止内存泄漏
        UserThreadLocal.remove();
    }
}
